package gosee

// RouterGroup 路由组结构体
type RouterGroup struct {
	prefix      string        // 路由组前缀
	parent      *RouterGroup  // 父路由组
	engine      *Engine       // 所有路由组共享一个 Engine 实例
	middlewares []HandlerFunc // 中间件
}

// normalizePath 标准化路径
// - 空路径自动设置为 "/"
// - 确保路径以 / 开头
func normalizePath(path string) string {
	if path == "" {
		return "/"
	}
	if path[0] != '/' {
		return "/" + path
	}
	return path
}

// Group 创建新的路由组
func (group *RouterGroup) Group(prefix string, middlewares ...HandlerFunc) *RouterGroup {
	prefix = normalizePath(prefix)
	if len(middlewares) == 0 {
		middlewares = []HandlerFunc{}
	}
	newGroup := &RouterGroup{
		prefix:      group.prefix + prefix,
		parent:      group,
		engine:      group.engine,
		middlewares: middlewares,
	}
	group.engine.groups = append(group.engine.groups, newGroup)
	return newGroup
}

// addRoute 是内部方法，处理路径拼接和路由注册逻辑
func (group *RouterGroup) addRoute(method, path string, handler HandlerFunc) {

	path = normalizePath(path)

	fullPath := group.prefix + path

	if fullPath[0] != '/' {
		fullPath = "/" + fullPath
	}

	group.engine.router.addRoute(method, fullPath, handler)
}

// GET 注册 GET 路由
func (group *RouterGroup) GET(path string, handler HandlerFunc) {
	group.addRoute("GET", path, handler)
}

// POST 注册 POST 路由
func (group *RouterGroup) POST(path string, handler HandlerFunc) {
	group.addRoute("POST", path, handler)
}

func (group *RouterGroup) Use(middlewares ...HandlerFunc) {
	if group.middlewares == nil {
		group.middlewares = make([]HandlerFunc, 0)
	}
	for _, m := range middlewares {
		if m != nil {
			group.middlewares = append(group.middlewares, m)
		}
	}
	// 确保中间件被添加到engine的groups列表中
	if group.engine != nil {
		group.engine.groups = append(group.engine.groups, group)
	}
}
